var wechatFlag = 0;
$(function() {
	// var tel=getCookie("loginName");
	// var pswd = getCookie("loginPwd");
	// var rememberMeFlag = getCookie("rememberMeFlag");
	// alert(tel + "," + pswd + "," + rememberMeFlag);
	// if(tel != null && tel != ""){
	// $("input").attr("checked","checked");
	// $.ajax( {
	// type : "POST",
	// url : contextPath+"/autoLogin.action",
	// async : false,//同步请求
	// data : {
	// loginPwd : pswd,loginName:tel, rememberMeFlag:rememberMeFlag
	// },
	// success : function(data) {
	// alert(data);
	// window.location.href= data;
	//				
	// }
	// });
	// }

	$('.flexslider').flexslider({
		directionNav : true,
		pauseOnAction : false,
		animation : "fade",
		slideshow : true,
		slideshowSpeed : 10000,
		keyboardNav : true,
		animationLoop : true,
		slideDirection : "horizontal"
	});

	$('#shake').DB_springMove({
		key : '13579111315171921',
		dir : 'y',
		mirror : 1,
		radius : 8,
		motionSpeed : 0.08
	});
	$('#shake_tw').DB_springMove({
		key : '13579111315171921',
		dir : 'y',
		mirror : 1,
		radius : 8,
		motionSpeed : 0.08
	});
	var tim = null, num = 120;
	var clickCount = false; // 记录是否点击过发送验证码
	$('.gain').on('click', function(event) {
		if (clickCount) { // 如果点击过直接返回
			return;
		}
		if (checkMobile()) {
			//弹出图形 验证码
			function resetImg() {
				$img.attr('src', contextPath + '/imageCode.action?rnd=' + Math.random());
			}
			var $content = $('<div style="text-align: center;font-family: 微软雅黑;"></div>');
			var $img = $('<img>');
			 $img.attr('src', contextPath + '/imageCode.action?rnd=' + Math.random())

			$img.click(resetImg)
			$content.append($('<div></div>').append($img));
			var $a = $('<a style="color: #FC6800;cursor: pointer;">换一张</a>');
			$a.click(resetImg);
			$content.append($('<div style="margin-top:15px;"></div>').append('<span>看不清？</span>').append($a));
			$content.append($('<div style="margin-top:15px"></div>').append('<input name="validateCode" style="width: 50%;height:22px;" placeholder="请输入图中的验证码">'))
			var $buttonConfirm = $('<div style="background:#FC6800;margin-top:25px;" class="free_btn" >确定</div>');
			$buttonConfirm.click(function(){
				clickCount = true;
				var validateCode = $.trim($content.find('input[name="validateCode"]').val());
				if(validateCode == ''){
					alert('请输入验证码！');
					clickCount = false; 
					return;
				}
				/*
				 * var test = setInterval(function() { num--; if( num == 0 ) {
				 * clearInterval(test); $('.gain').html('获取验证码');
				 * $('.gain').css({'background':'#74BB22','color':'#fff'});
				 * $('.cover').hide(); num=60; }else{ $('.cover').show();
				 * $('.gain').html('('+num+'s)后重新获取');
				 * $('.gain').css({'background':'#CCCCCC','font-size':'12px','color':'#666666'}); }
				 * },1000);
				 */
				$.ajax({
					type : "POST",
					url : contextPath + "/randCodeNew.action",
					async : false,// 同步请求
					data : {
						mobile : $("#mobile").val(),
						userValidateCode : validateCode,
						type : 'registor',
						currentTime : $("#currentTime").val(),
						codeSign : $("#codeSign").val()
					},		
					success : function(data) {
						if (data == "true") {
							// readSecend();
							var test = setInterval(function() {
								num--;
								if (num == 0) {
									clearInterval(test);
									$('.gain').html('获取验证码');
									$('.gain').css({
										'background' : '#FC6800',
										'color' : '#fff'
									});
									$('.cover').hide();
									num = 120;
									clickCount = false; 
								} else {
									$('.cover').show();
									$('.gain').html('(' + num + 's)后重新获取');
									$('.gain').css({
										'background' : '#CCCCCC',
										'font-size' : '12px',
										'color' : '#666666'
									});
								}
								d.close().remove();
							}, 1000);
						} else {
							if (data == "codeError") {
								alert("验证码错误！");
								clickCount = false; 
							} else if (data == "sendMessageFail") {
								alert("短信发送失败，请联系管理员！");
							} else if (data == "moreThan5Times") {
								alert("短信发送次数超过5次，请联系管理员！");
								$("#code").attr("disabled", "false");
							} else if (data == "timeOut") {
								alert("请求超时！");
							} else if (data == "error") {
								alert("非法请求！");
							}
							return false;
						}
					}
				});
			})
			$content.append($buttonConfirm);
			var d = dialog({
			    title: '请输入图形验证码',
			    width: 400,
			    content: $content
			});
			d.showModal();
			event.stopPropagation();
		}else{
			clickCount = false; 
		}
	});

	// $('.immediately_btn').on('click',function ( event ) {
	// Hve();
	// });
	$('#loginForm').submit(function() {
		var rememberMeFlag = 0;
		var tel = $('#telphone').val();
		var pswd = $('#password').val();
		var signData = $('#sign').val();
		var isGw = $('#isgw').val();

		if (document.getElementById("rememberMe").checked) {
			rememberMeFlag = 1;
			setCookie("loginName", tel);
			setCookie("loginPwd", pswd);
			setCookie("rememberMeFlag", rememberMeFlag);
		}

		if ((tel == '' || pswd == '') && isGw != "true") {
			$('.mix_he').css({
				'border' : '1px solid #ed6d00'
			});
			$('.mix_he h5 span').text('请输入手机号或密码');
			$('.mix_he h5').show();
			return false;
		} else {
			var flag = true;
			$.ajax({
				type : "POST",
				url : contextPath + "/existsUser.action",
				async : false,// 同步请求
				data : {
					phone : tel
				},
				success : function(data) {
					if (data == "false") {
						$('.mix_he').css({
							'border' : '1px solid #ed6d00'
						});
						$('.mix_he h5 span').text('账号不存在');
						$('.mix_he h5').show();
						flag = false;
					}
				},
				error : function() {
					flag = false;
				}
			});
			if (!flag) {
				return false;
			} else {
				$.ajax({
					type : "POST",
					url : contextPath + "/checkUserType.action",
					async : false,// 同步请求
					data : {
						phone : tel
					},
					success : function(data) {
						if (data == "false") {
							$('.mix_he').css({
								'border' : '1px solid #ed6d00'
							});
							$('.mix_he h5 span').text('无效的账号不能登录');
							$('.mix_he h5').show();
							flag = false;
						}
					},
					error : function() {
						flag = false;
					}
				});
			}
			if (!flag) {
				return false;
			} else {
				//微信扫码登录
				if(wechatFlag == 1){
					tel = tel + " ";
					$('#telphone').val(tel + " ");
				}
				$.ajax({
					type : "POST",
					url : contextPath + "/checkPswd.action",
					async : false,// 同步请求
					data : {
						loginPwd : pswd,
						loginName : tel,
						rememberMeFlag : rememberMeFlag,
						ticket : $("#ticket").val(),
						sign : signData,
						isgw : isGw
					},
					success : function(data) {
						if (data == "false") {
							flag = false;
						}

					},
					error : function() {
						flag = false;
					}
				});
				if (!flag) {
					$('.mix_he').css({
						'border' : '1px solid #ed6d00'
					});
					$('.mix_he h5 span').text('密码错误');
					$('.mix_he h5').show();
					return false;
				}
			}
		}
	});
	$("#toRegistor").click(function() {
		$("#loginDiv").addClass("rotateAnimate");
		setTimeout(function() {
			$("#loginDiv").addClass("an_hide").removeClass("rotateAnimate");
			$("#registorDiv").removeClass("an_hide");
		}, 550);
		$('.mix_hee').css({
			'border' : 'none'
		});
		/*
		 * $("#loginDiv").addClass("an_hide");
		 * $("#registorDiv").removeClass("an_hide");
		 */
	});
	$("#toLogin").click(function() {
		$("#registorDiv").addClass("rotateAnimate");
		setTimeout(function() {
			$("#registorDiv").addClass("an_hide").removeClass("rotateAnimate");
			$("#loginDiv").removeClass("an_hide");
		}, 550);
		$('.mix_he').css({
			'border' : 'none'
		});
		/*
		 * $("#registorDiv").addClass("an_hide");
		 * $("#loginDiv").removeClass("an_hide");
		 */
	});

	function Hve() {
		var cono = $('.pan').val(), pas = $('.pas').val();
		$('.mix_he').css({
			'border' : '1px solid #ed6d00'
		});
		if (cono == '' || pas == '') {
			$('.mix_he h5').show();
		}
		;
	}
	;

	$('.pan,.pas').on('focus', function(event) {
		$('.mix_he').css({
			'border' : '1px solid #D8D8D8'
		});
		$('.mix_he h5').hide();
		$('.mix_hee').css({
			'border' : '1px solid #D8D8D8'
		});
		$('.registorError').hide();
	});
	$("#registorBtn").click(
			function() {
				if (checkMobile() && checkCode() && checkPswd()) {
					// $("#registorForm").submit();
					$.ajax({
						type : "POST",
						url : contextPath + "/registorUser.action",
						data : {
							mobile : $("#mobile").val(),
							password : $("#pswd").val(),
							ticket : $("#ticket").val()
						},
						async : false,// 同步请求
						success : function(data) {
							if (data == "-1") {
								alert("注册失败");
							} else {
								window.location.href = contextPath
										+ "/activationLoginInput.action";
							}
						},
						error : function() {
							flag = false;
						}
					});
				} else {
					return false;
				}
			});
	function checkMobile() {
		var txt = $.trim($('#mobile').val());
//		var photo = /^((13[0-9]{1})|159|153|156|150|152|158|151|157|155|188|185|189|186|187|181|180|182|147|184|183|170|177|178|176|145)+\d{8}$/;
		var photo = /^(0|86|17951)?(13[0-9]|15[012356789]|17[0-9]|18[0-9]|14[57])[0-9]{8}$/;
		if (txt == '') {
			$('.mix_hee').css({
				'border' : '1px solid #ed6d00'
			});
			$('.registorError span').text('请输入手机号');
			$('.registorError').show();
			return false;
		}
		if (photo.test(txt) == false) {
			$('.mix_hee').css({
				'border' : '1px solid #ed6d00'
			});
			$('.registorError span').text('您输入的账号有误，请重新输入');
			$('.registorError').show();
			return false;
		}
		var flag = true;
		$.ajax({
			type : "POST",
			url : contextPath + "/existsUser.action",
			async : false,// 同步请求
			data : {
				phone : txt
			},
			success : function(data) {
				if (data == "false") {
					flag = false;
				}
			},
			error : function() {
				flag = false;
			}
		});
		if (flag) {
			$('.mix_hee').css({
				'border' : '1px solid #ed6d00'
			});
			$('.registorError span').text('您输入的账号已注册');
			$('.registorError').show();
			return false;
		}
		return true;
	}

	function checkCode() {
		var code = $('#code').val();
		if (code == '') {
			$('.mix_hee').css({
				'border' : '1px solid #ed6d00'
			});
			$('.registorError span').text('请输入短信验证码');
			$('.registorError').show();
			return false;
		} else {
			var flag = true;
			$.ajax({
					type : "POST",
					url : contextPath + "/comparison.action",
					data : {
						valCode : code
					},
					async : false,// 同步请求
					success : function(data) {
						if (data == "") {
							flag = true;
						} else {
							flag = false;
							$('.mix_hee').css({
								'border' : '1px solid #ed6d00'
							});
							if (data == "moreThan5Times") {
								$('.registorError span').text(
										'发送验证码已超过5次，请联系管理员！');
							} else if (data == "tooOld") {
								$('.registorError span').text('验证码已过期！');
							} else if (data == "codeError") {
								$('.registorError span').text('验证码错误！');
							} else if (data == "sendMessageFail") {
								$('.registorError span').text('短信验证码发送失败！');
							}
							$('.registorError').show();
						}
					}
				});
			return flag;
		}
	}
	/*
	 * $('#code').keyup(function(){ if(checkCode()){ $(this).before('<a
	 * href="javascript:;" class="yes_btn"></a>'); } else{
	 * $(this).prev(".yes_btn").remove(); } });
	 */
	$('#code').keyup(function() {
		$(this).prev().find("a").remove();
	});
	function checkPswd() {
		var pswd = $('#pswd').val();
		if (pswd == '') {
			$('.mix_hee').css({
				'border' : '1px solid #ed6d00'
			});
			$('.registorError span').text('请输入密码');
			$('.registorError').show();
			return false;
		} else {
			var pattern = /^\w{6,16}$/;
			if (!pswd.match(pattern)) {
				$('.mix_hee').css({
					'border' : '1px solid #ed6d00'
				});
				$('.registorError span').text('请输入6-16位以字母、数字或下划线组成的密码');
				$('.registorError').show();
				return false;
			}
		}
		return true;
	}
	var doc = document, inputs = doc.getElementsByTagName('input'), supportPlaceholder = 'placeholder' in doc
			.createElement('input'), placeholder = function(input) {
		var text = input.getAttribute('placeholder'), defaultValue = input.defaultValue;
		if (defaultValue == '') {
			input.value = text;
			input.setAttribute("old_color", input.style.color);
			input.style.color = "#c0c0c0";
		}
		;
		input.onfocus = function() {
			this.style.color = this.getAttribute("old_color");
			if (input.value === text) {
				this.value = '';
			}
			;
		};
		input.onblur = function() {
			if (input.value === '') {
				this.style.color = "#c0c0c0";
				this.value = text;
			}
			;
		};
	};
	if (!supportPlaceholder) {
		for (var i = 0, len = inputs.length; i < len; i++) {
			var input = inputs[i], text = input.getAttribute('placeholder');
			if (input.type === 'text' && text) {
				placeholder(input);
			}
		}
	}
	;

	var serviceUrl = $("#serviceUrl").val();
	if (serviceUrl.length < 1) {
		removeCookie("loginName");
		removeCookie("loginPwd");
		removeCookie("rememberMeFlag");
	}
	var tel = getCookie("loginName");
	var pswd = getCookie("loginPwd");
	var rememberMeFlag = getCookie("rememberMeFlag");
	var telephone = $("#gwMobile").val();
	var gwPswd = $("#gwPswd").val();
	
	if (tel != null && tel != "" && pswd != null && rememberMeFlag == 1) {
			$("#rememberMe").attr("checked", "checked");
			$("#telphone").val(tel);
			$("#password").val(pswd);
			$('#loginForm').submit();
	} 
	if(telephone != null && telephone != ""){
		var sign = "";
		if(telephone.indexOf(".") != -1){
			var arr = telephone.split(".");
			telephone = arr[0];
			sign = arr[1];
		}
		//telephone = telephone.substring(0,str.length-1);
		$("#telphone").val(telephone);
		$("#password").val(gwPswd);
		$("#sign").val(sign);
		$("#isgw").val("true");

		$('#loginForm').submit();
	}

});

// 设置Cookie
function setCookie(c_name, value) {
	var expiredays = 30;
	var exp = new Date();
	exp.setTime(exp.getTime() + expiredays * 24 * 60 * 60 * 1000);
	document.cookie = c_name + "=" + escape(value) + ";expires="
			+ exp.toGMTString() + ";path=/";
}

// 获取Cookie
function getCookie(name) {
	var value = document.cookie.match(new RegExp("(^| )" + name
			+ "=([^;]*)(;|$)"));
	if (value != null) {
		return decodeURIComponent(value[2]);
	} else {
		return null;
	}
}

// 删除cookie
function removeCookie(name) {
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var cval = getCookie(name);
	if (cval != null) {
		document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString()
				+ ";path=/";
	}
}
